﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KUMA.CellularAutomata.HelperLibrary
{
   public static class RuleHelper
   {
       public static bool GetAliveState(Cell TargetCell, List<Cell> Cells)
       {
           bool ret = false;//代表死亡
           //1.获取目标周围的8个细胞
           List<Cell> AroudCells =
               Cells.FindAll(o => ((o.CellX >= TargetCell.CellX - 1 && o.CellX <= TargetCell.CellX + 1)
                                   && (o.CellY >= TargetCell.CellY - 1 && o.CellY <= TargetCell.CellY + 1)))
                   .ToArray().ToList();
           
           // X>= 目标的X-1 且<= 目标X+1
           // Y同上
           //移除自身
           AroudCells.Remove(AroudCells.Find(o => (o.CellX == TargetCell.CellX) && (o.CellY == TargetCell.CellY)));
           ret = Rule(TargetCell, AroudCells);
           return ret;
       }


       /// <summary>
       /// 1号规则 活着的细胞 周围小于2个细胞存活 则此细胞死亡
       /// 2号规则 活着的细胞 周围大于3个细胞存活 则次细胞死亡
       /// 3号规则 死亡的细胞 周围大于2个细胞存活 则此细胞复活
       /// </summary>
       /// <param name="TargetCell">目标细胞</param>
       /// <param name="Cells">周围的细胞</param>
       /// <returns></returns>
       private static bool Rule(Cell TargetCell,List<Cell> Cells)
       {
           bool ret = false;//代表死亡
           int AruondCellAliveInt = Cells.Count(o => o.IsAlive);//获取周边细胞的存活状态
           if (TargetCell.IsAlive)
           {
               ret = (AruondCellAliveInt >= 2) && (AruondCellAliveInt <= 3);//1 2 4规则合并 即周边有2 3个细胞时才存活 否则都会死亡
           }
           else
           {
               ret = (AruondCellAliveInt > 2);//3规则 死亡细胞周边如果有3个即以上细胞 则复活
           }
           return ret;
       }

   }
}
